//
//  NetworkTool.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/28.
//

import UIKit
import Moya
import CoreTelephony
class NetworkTool: NSObject {
    
    class func request(_ api:EPApi ,_ callback:((_ response: NSDictionary)->Void)?)
    {
        ///api = EPApi.history
        let order = MoyaProvider<EPApi>()
        order.request(api) { result in
            switch result {
            case let .success(result):
                do {
                    try print("result.mapJSON() = \(result.mapJSON())")
                    callback?(try result.mapJSON() as! NSDictionary)
                } catch {
                    print("MoyaError.jsonMapping(result) = \(MoyaError.jsonMapping(result))")
                }
            case let .failure(result):
                switch result{
                case .underlying:
                    callback?(["code":NSNumber(value: 10000),"msg":"请检查网络状态"])
                default:
                    break
                }
                break
            }
            print("result = \(result)")
        }
    }
    
    
    ///上传数据
    class func upload(_ record:Record,_ block:(()->Void)?=nil){
     
        if record.data.count <= 0{
            return RLHud.start(LS("当前没有有效数据"), stopTime:1)
        }
        
        let uuid = self.deviceUUID()
        var para :[String:Any] = ["endTime":record.endTime,"startTime":record.startTime,"tester":record.tester,"email":record.email,"phoneMac":uuid]
        var list = [Any]()
        let array  = record.data as? [SingleData] ?? [SingleData]()
        for model in array{
            if model.l_data.length > 0{
                let string = model.l_data.substring(to: model.l_data.length - 1)
                let dict = ["broadcastName":model.deviceName,"doingCount":model.num,"doingTime":NSDate.transToDate("yyyy-MM-dd HH:mm:ss", model.stamp.intValue()),"pressureValue":string] as [String : Any]
                list.append(dict)
            }
            if model.r_data.length > 0{
                let string = model.r_data.substring(to: model.r_data.length - 1)
                let dict = ["broadcastName":model.deviceName,"doingCount":model.num,"doingTime":NSDate.transToDate("yyyy-MM-dd HH:mm:ss", model.stamp.intValue()),"pressureValue":string] as [String : Any]
                list.append(dict)
            }
        }
        para["activeDoingList"] = list
        [NetworkTool.request(EPApi.upload(para), { response in
            let code = (response.value(forKey: "code") as? NSNumber ?? NSNumber(value: 0)).intValue
            if code == 200{
                self.deleteLocal(record) { success in
                    block?()
                }
                RLHud.start(LS("发送成功"), stopTime:1)
            }else if code == 10000{
                record.noUpload = true
                record.bg_saveOrUpdateAsync { success in }
                RLHud.start(LS("无网络，当前数据保存至本地"), stopTime: 1) {
                    record.currentVC().navigationController?.popToRootViewController(animated: true)
                }
            } else{
                RLHud.start(LS("发送失败"), stopTime:1)
            }
        })]
    }
    
    
    ///导出数据
    class func download(_ record:Record ,_ block:(()->Void)?=nil){
        if record.data.count > 0 {
            self.upload(record, block)
        }else{
            NetworkTool.request(EPApi.download(record.email, Int(record.recordId)), { response in
                let code = (response.value(forKey: "code") as? NSNumber ?? NSNumber(value: 0)).intValue
                if code == 200{
                    RLHud.start("导出成功", stopTime: 1, handle: nil)
                    block?()
                }else{
                    let msg = response.value(forKey: "msg") as? String ?? ""
                    RLHud.start(msg, stopTime: 1, handle: nil)
                }
            })
        }
    }
    
    
    ///删除本地数据
    class func deleteLocal(_ record:Record ,_ block:((_ success:Bool)->Void)?){
        let str = String(format:"where %@=%@", bg_sqlKey("recordId"),bg_sqlValue("\(record.recordId)"))
        Record.bg_deleteAsync(nil, where: str) { success in
            print(">>>>>>>>>>>>>>>>a删除本地数据\(success)")
            block?(success)
        }
    }
}
